package cn.jn.lhm.netty.part10;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lhm 2753914576@qq.com
 * @time 2024/10/20 - 上午1:40
 **/
@Slf4j
public class NettyServer {
    public static void main(String[] args) {
        NettyServer server = new NettyServer();
        server.start(9999);
    }

    private void start(int port) {
        EventLoopGroup boos = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup(2);
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap()
                    .group(boos, worker)
                    .channel(NioServerSocketChannel.class)
                    // 指定服务端的处理器
                    .handler(new LoggingHandler(LogLevel.INFO))
                    // 指定连接的客户端的处理器Z
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        /**
                         * 改方法会在客户端连接成功后，创建新的channel，并且给该channel添加处理器
                         */
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new ServerHandler1()).addLast(new ServerHandler2());
                        }
                    });
            ChannelFuture future = serverBootstrap.bind(port).sync();
            // 监听ServerSocketChannel关闭，不关闭则会在这里阻塞
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("netty server error", e);
        } finally {
            // 关闭资源
            boos.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}
